package com.zrj.auth.core.userdetails.user;

import cn.hutool.core.collection.CollectionUtil;
import com.zrj.auth.constant.GlobalConstants;
import com.zrj.auth.pojo.dto.AuthUserDTO;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author zhaorujie
 */
@Data
public class SysUserDetails implements UserDetails {

    private long userId;
    private String username;
    private String password;
    private boolean enabled;
    private Collection<SimpleGrantedAuthority> authorities;

    public SysUserDetails(AuthUserDTO auth) {
        this.setUserId(auth.getUserId());
        this.setUsername(auth.getUsername());
        this.setPassword(auth.getPassword());
        this.setEnabled(GlobalConstants.STATUS_YES.equals(auth.getStatus()));
        if (CollectionUtil.isNotEmpty(auth.getRoles())) {
            authorities = new ArrayList<>();
            auth.getRoles().forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
        }
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
